<?php

/**
 * Created by PhpStorm.
 * User: li
 * Date: 15-12-6
 * Time: 下午8:23
 */
class Activities_model extends MY_Model
{
    function __construct(){
        parent::__construct();
        $this->_table_name = 'activity';
    }

    function sold_out($activity_id){
        $this->db->where('id',$activity_id);
        $this->db->set('is_sold',0);
        $this->db->update($this->_table_name);
        return $this->db->affected_rows()>0;
    }

    function sold_in($activity_id){
        $this->db->where('id',$activity_id);
        $this->db->set('is_sold',1);
        $this->db->update($this->_table_name);
        return $this->db->affected_rows()>0;
    }

    function get_activity_name($activity_id){
        $this->db->select('id,name');
        $this->db->where('id',$activity_id);
        $this->db->limit(1);
        $query = $this->db->get($this->_table_name);
        if($query->num_rows()>0){
            return $query->result_array()[0];
        }
        return null;
    }


    function get_activities(array $conditions,array $fields,array $options){


        $selected = '';
        if(!empty($fields)){
            if(count($fields)>0){
                foreach($fields as $value){
                    $selected .= $this->_table_name.'.'.$value.',';
                }
                $selected = rtrim($selected,',');
            }
        }
        if($selected=='')
            $this->db->select($this->_table_name.'*');
        else
            $this->db->select($selected);

        $this->db->select('lecturer.name as lecturer_name,lecturer.intro as lecturer_intro,lecturer.avatar as lecturer_avatar,
        lecturer.score as lecturer_score');
        $this->db->select('place.name as place_name,place.cover as place_avatar,
        place.score as place_score,place.address as place_address,place.traffic as place_traffic');//,place.intro as place_intro

        $this->db->join('place','activity.place_id=place.id','left');
        $this->db->join('lecturer','activity.lecturer_id=lecturer.id','left');


        $this->db->where('activity.is_del',0);
        if(isset($options['limit'])){
            $this->db->limit($options['limit'][0],$options['limit'][1]);
        }
        if(isset($options['order'])){
            $this->db->order_by($this->_table_name.'.'.$options['order'][0]);
        }
        if(!empty($conditions)){
            if(count($conditions)>0){
                foreach($conditions as $key=>$value){
                    $this->db->where($this->_table_name.'.'.$key,$value);
                }
            }
        }


        $query = $this->db->get($this->_table_name);
        if($query->num_rows()>0){
            return $query->result_array();
        }
        return null;
    }

    function sold_increment($id,$num){
        return $this->set_increment('sold',$id,$num);
    }
}